﻿/**
 * 安装  PM> Install-Package EasyNetQ
 */

using System;
using EasyNetQ;

namespace MQHelper
{
    public class MqManage
    {

        /// <summary>
        /// 发送消息
        /// </summary>
        public static void Publish(MyMessage msg)
        {
            //// 创建消息bus
            IBus bus = RabbitHutch.CreateBus("host=192.168.1.117;virtualHost=/;username=ypf;password=123456");

            try
            {
                bus.Publish(msg, x => x.WithTopic(msg.MessageRouter));
            }
            catch (EasyNetQException ex)
            {
                //处理连接消息服务器异常 
            }

            bus.Dispose();//与数据库connection类似，使用后记得销毁bus对象
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="msg"></param>
        public static void Subscribe(MyMessage msg)
        {
            //// 创建消息bus
            IBus bus = RabbitHutch.CreateBus("host=192.168.1.117;virtualHost=/;username=ypf;password=123456");

            try
            {
                bus.Subscribe<MyMessage>(msg.MessageRouter, message => Console.WriteLine(message.MessageBody), x => x.WithTopic(msg.MessageRouter));
            }
            catch (EasyNetQException ex)
            {
                //处理连接消息服务器异常 
            }
        }

    }
}